<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<jsp:include page="../fragments/headTag.jsp" />
<body>
	<jsp:include page="../fragments/bodyHeader.jsp" />

	<script type="text/javascript">
		(function($) {
			$(document).ready(function() {
				updateUrl('/eyeq-chat/chat/chat-handler');
				connect();
				
				$("#btn-input").keyup(function(event) {
					if(event.keyCode == "13") {
						sendMessage();
					}
				});

				$("#btn-chat").click(function(event) {
					sendMessage();
				});
			});
		})(jQuery);

		var ws = null;
		var url = null;
		var transports = [];

		function setConnected(connected) {
			//연결이 되었을 때 버튼과 채팅방 변화.
			//document.getElementById('btn-input').disabled = !connected;
			//document.getElementById('disconnect').disabled = !connected;
			//document.getElementById('echo').disabled = !connected;
		}

		//웹 소켓에 연결하는 함수.
		function connect() {
			if (!url) {
				alert('Select whether to use W3C WebSocket');
				return;
			}

			ws = new WebSocket(url);

			//소켓 접근시 할 동작.
			ws.onopen = function() {
				setConnected(true);
				//printMessage('Info: connection opened.');
			};

			//메시지가 서버로부터 넘어왔을 시 할 동작.
			ws.onmessage = function(event) {
				var data = event.data;
				data = $.parseJSON(data);
				console.log(data);
				if (data != null && data != "") {
					printMessage(data.message, data.userName);
					if(data.currentUsers) {
						printCurrentUsers(data.currentUsers);
					}
				}
			};

			//소켓 연결이 끊어졌을 시 할 동작.
			ws.onclose = function(event) {
				setConnected(false);
				//printMessage('Info: connection closed.');
				printMessage(event);
			};
		}

		//연결 끊기.
		function disconnect() {
			if (ws != null) {
				ws.close();
				ws = null;
			}
			setConnected(false);
		}

		//메시지를 보냄.
		function sendMessage() {
			if (ws != null) {
				var btnInput = $("#btn-input");
				var message = btnInput.val();

				if (message != null && message != "") {
					printMessage(message);
					ws.send(message);
					btnInput.val("");
				}
			} else {
				alert('connection not established, please connect.');
			}
		}

		function updateUrl(urlPath) {
			/* 			if (urlPath.indexOf('sockjs') != -1) {
			 url = urlPath;
			 document.getElementById('sockJsTransportSelect').style.visibility = 'visible';
			 } else { */
			if (window.location.protocol == 'http:') {
				url = 'ws://' + window.location.host + urlPath;
			} else {
				url = 'wss://' + window.location.host + urlPath;
			}
			//document.getElementById('sockJsTransportSelect').style.visibility = 'hidden';
			//}
		}

		/* function updateTransport(transport) {
			transports = (transport == 'all') ? [] : [ transport ];
		} */

		
		function printCurrentUsers(currentUsersObj) {
			var currentUsers = $(".chat-main ul.current-users");
			//자식노드 전부 삭제 후에 현재 유저를 넣음.
			currentUsers.empty();
			$.each(currentUsersObj, function(key, value) {
				var wrap = $(document.createElement("li")).attr({
					"class" : "left clearfix"
				});
				var userImgSpan = $(document.createElement("span")).attr({
					"class" : "user-img pull-left"
				});

				var userImg = $(document.createElement("img")).attr({
					"src" : "http://placehold.it/50/55C1E7/fff&text=U",
					"alt" : "User Avatar",
					"class" : "img-circle"
				});

				var userBody = $(document.createElement("div")).attr({
					"class" : "user-body clearfix"
				});

				var userBodyHeader = $(document.createElement("div")).addClass(
						"header");
				var primaryFont = $(document.createElement("strong")).addClass(
						"primary-font");

				userImgSpan.append(userImg);
				primaryFont.text(value);

				userBodyHeader.append(primaryFont);
				userBody.append(userBodyHeader);

				wrap.append(userImgSpan);
				wrap.append(userBody);

				currentUsers.append(wrap);
			});
		}

		function printMessage(message, userName) {
			var chat = $(".chat-main ul.chat");
			var wrap = $(document.createElement("li")).addClass("left")
					.addClass("clearfix");

			var chatImgSpan = $(document.createElement("span")).addClass(
					"chat-img").addClass("pull-left");

			var chatImg = $(document.createElement("img")).attr({
				"src" : "http://placehold.it/50/55C1E7/fff&text=U",
				"alt" : "User Avatar",
				"class" : "img-circle"
			});

			var chatBody = $(document.createElement("div")).addClass(
					"chat-body").addClass("clearfix");

			var chatBodyHeader = $(document.createElement("div")).addClass(
					"header");
			var primaryFont = $(document.createElement("strong")).addClass(
					"primary-font");
			var textMuted = $(document.createElement("small")).attr({
				"class" : "pull-right text-muted"
			});
			var glyphiconTime = $(document.createElement("span")).attr({
				"class" : "glyphicon glyphicon-time"
			});
			var content = $(document.createElement("p")).text(message);

			chatImgSpan.append(chatImg);

			userName = userName ? userName
					: "<c:out value="${sessionScope.user.name}" />";
			primaryFont.text(userName);
			chatBodyHeader.append(primaryFont);
			textMuted.append(glyphiconTime).text("12 mins ago");
			chatBodyHeader.append(textMuted);

			chatBody.append(chatBodyHeader);
			chatBody.append(content);

			wrap.append(chatImgSpan);
			wrap.append(chatBody);

			chat.append(wrap);

			var panelBody = $(".panel-body");
			var chatHeight = panelBody.find(".chat").height();
			panelBody.scrollTop(chatHeight);
			/*
			<li class="left clearfix">
				<span class="chat-img pull-left">
					<img src="http://placehold.it/50/55C1E7/fff&text=U"
						alt="User Avatar" class="img-circle" />
				</span>
				<div class="chat-body clearfix">
					<div class="header">
						<strong class="primary-font">Masud</strong> 
						<small
							class="pull-right text-muted"> 
							<span class="glyphicon glyphicon-time"></span>12 mins ago
						</small>
					</div>
					<p>Lorem ipsum dolor sit amet, consectetur adipiscing
						elit. Curabitur bibendum ornare dolor, quis ullamcorper
						ligula sodales.
					</p>
				</div>
			</li>
			 */
		}
	</script>
	<noscript>
		<h2 style="color: #ff0000">Seems your browser doesn't support
			Javascript! Websockets rely on Javascript being enabled. Please
			enable Javascript and reload this page!</h2>
	</noscript>
	<div class="chat-main">
		<div class="container">
			<div class="row">
				<div class="col-md-9">
					<div class="panel panel-primary">
						<div class="panel-heading">
							<span class="glyphicon glyphicon-comment">
							</span> EYEQ 채팅방
							<div class="btn-group pull-right">
								<button type="button"
									class="btn btn-default btn-xs dropdown-toggle"
									data-toggle="dropdown">
									<span class="glyphicon glyphicon-chevron-down"></span>
								</button>
								<ul class="dropdown-menu slidedown">
									<li>
										<a href="#"><span class="glyphicon glyphicon-refresh"></span>Refresh</a>
									</li>
									<li>
										<a href="#"><span class="glyphicon glyphicon-ok-sign"></span>Available</a>
									</li>
									<li>
										<a href="#"><span class="glyphicon glyphicon-remove"></span>Busy</a>
									</li>
									<li>
										<a href="#"><span class="glyphicon glyphicon-time"></span>Away</a>
									</li>
									<li class="divider"></li>
									<li>
										<a href="#"><span class="glyphicon glyphicon-off"></span>Sign Out</a>
									</li>
								</ul>
							</div>
						</div>
						<div class="panel-body">
							<ul class="chat">
								<!-- <li class="left clearfix">
									<span class="chat-img pull-left">
										<img src="http://placehold.it/50/55C1E7/fff&text=U"
											alt="User Avatar" class="img-circle" />
									</span>
									<div class="chat-body clearfix">
										<div class="header">
											<strong class="primary-font">Masud</strong> 
											<small
												class="pull-right text-muted"> 
												<span class="glyphicon glyphicon-time"></span>12 mins ago
											</small>
										</div>
										<p>Lorem ipsum dolor sit amet, consectetur adipiscing
											elit. Curabitur bibendum ornare dolor, quis ullamcorper
											ligula sodales.
										</p>
									</div>
								</li> -->
							</ul>
						</div>
						<div class="panel-footer">
							<div class="input-group">
								<input id="btn-input" type="text" class="form-control input-sm"
									placeholder="Type your message here..." /> 
								<span class="input-group-btn">
									<button class="btn btn-warning btn-sm" id="btn-chat">Send</button>
								</span>
							</div>
						</div>
					</div>
				</div>
				<div class="col-md-3">
					<div class="panel panel-primary">
						<div class="panel-heading">
							<span class="glyphicon glyphicon-comment">
							</span> 현재 접속자 목록
						</div>
						<div class="panel-body">
							<ul class="current-users">
								<!-- <li class="left clearfix">
									<span class="chat-img pull-left">
										<img src="http://placehold.it/50/55C1E7/fff&text=U"
											alt="User Avatar" class="img-circle" />
									</span>
									<div class="chat-body clearfix">
										<div class="header">
											<strong class="primary-font">Masud</strong> 
											<small
												class="pull-right text-muted"> 
												<span class="glyphicon glyphicon-time"></span>12 mins ago
											</small>
										</div>
										<p>Lorem ipsum dolor sit amet, consectetur adipiscing
											elit. Curabitur bibendum ornare dolor, quis ullamcorper
											ligula sodales.
										</p>
									</div>
								</li> -->
							</ul>
						</div>
					</div>
				</div>
			</div>
		</div>
		<jsp:include page="../fragments/footer.jsp" />
	</div>
</body>
</html>
